package me.ezitku.base.extensions


import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import androidx.fragment.app.Fragment
import android.telephony.TelephonyManager
import android.widget.TextView
import com.pawegio.kandroid.wifiManager
import com.ug_project.Async.runASync
import com.ug_project.adapters.createBaseAdapter
import com.ug_project.views.baseShowToast
import com.ug_project.views.findTextView
import me.ezitku.base.R
import java.util.*

//private val Activity.contentView: ViewGroup
//    get() = (findViewById(android.R.id.content) as ViewGroup)


/**
 * Start Activity,Service
 */
fun Context.startActivity(cls: Class<*>) {
    this.startActivity(android.content.Intent(this, cls))
}

fun Fragment.startActivity(cls: Class<*>) {
    activity!!.startActivity(cls)
}


fun Context.startService(cls: Class<*>) {
    this.startService(android.content.Intent(this, cls))
}


/**
 * Device Id ,Mac Id
 */
val Context.deviceId: String
    @SuppressLint("MissingPermission", "HardwareIds")
    get() {
        val telephonyManager = this.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return try {
            telephonyManager.deviceId
//            telephonyManager.getDeviceId()
        } catch (e: Exception) {
            "123456789"
        }
    }

val Fragment.deviceId: String
    get() {
        return activity!!.deviceId
    }

val Context.wifiMacId: String
    @SuppressLint("MissingPermission", "HardwareIds")
    get() {
        return wifiManager?.connectionInfo!!.macAddress
    }
val String.isPhone: Boolean
    get() {
        return length == 11
    }


// ====


fun TextView.countTime(time: Int = 60, text: String = "تەستىق نۇمۇر يوللاڭ") {
    this.isEnabled = false
    runASync {
        for (i in time downTo 0) {
            runUI {
                this@countTime.text = "$i s"
            }
            delay(1000)
        }
        runUI {
            this@countTime.isEnabled = true
            this@countTime.text = text
        }

    }
}

/**Toast*/
fun Activity.successToast() {
    baseShowToast(getString(R.string.text_success))
}


fun Fragment.successToast() {
    activity!!.baseShowToast(getString(R.string.text_success))
}

//بىرلا item سى بار Adapter
/**
 * @param data بارلىق ئۇچۇر
 * @param action ھەر بىر item غا باغلايدىغان ئۇچۇر قايتۇرۇپ بېرىمىز
 */
fun <T> Context.getAdapter(data: ArrayList<T>, action: (position: Int) -> String): android.widget.BaseAdapter {
    return createBaseAdapter(this, R.layout.item_spinner, data) {
        GetView { position, convertView, parent, data ->
            var content = convertView.findTextView(R.id.item)
            content.text = action(position)
        }
    }
}


fun tryCatch(action: () -> Unit) {
    try {
        action()
    } catch (e: Exception) {
    }
}

